//
//  RBDataBaseManager2.m
//  FD
//
//  Created by xiaofang wang on 2019/1/14.
//  Copyright © 2019年 ZhiYuan Network. All rights reserved.
//
//  RBDataBaseManager.m
//  FD
//
//  Created by xiaofang wang on 2018/11/22.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  本地数据库
/**
 sql 数据类型
 blod NSData,可用于image、归档后的对象
 */
//数据库名字 fudi.sqlite
//表名 msgTable

#import "RBDataBaseManager2.h"
#import "FMDB.h"

@interface RBDataBaseManager2()
//databaseQueue对象 线程安全的
@property (nonatomic, strong) FMDatabaseQueue *dbQueue;

@end

@implementation RBDataBaseManager2
#pragma mark - 一 初始化数据库
//单例对象
+ (instancetype)shareDataBaseQueueManager {
    static RBDataBaseManager2 *manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[RBDataBaseManager2 alloc] init];
    });
    
    return manger;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //1.获取沙盒路径
        NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        
        //2.创建数据库文件路径
        NSString *path = [dir stringByAppendingPathComponent:@"fudi.sqlite"]; //数据库名字
        FDLog(@"本地数据库路径:%@",path);
        
        //3.根据路径创建一个FMDataBaseQueue对象
        self.dbQueue = [[FMDatabaseQueue alloc] initWithPath:path];
        //4.创建一张表
        [self createMessageTable];
    }
    return self;
}

- (void)createMessageTable {
    
    NSString *sqlStr = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS msgTable(msgId TEXT PRIMARY KEY NOT NULL, content bolb)"]; //bolb 存放 NSData类型
    
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        if ([db executeUpdate:sqlStr]) {
            FDLog(@"创建表成功");
        }else {
            FDLog(@"创建表失败");
        }
    }];
}


#pragma mark - 二 接口

/**1.插入一个数据**/
- (void)addMessageModel:(PushMsgModel *)model {
    //    NSString *sqlStr = [NSString stringWithFormat:@"INSERT INTO msgTable(bookId, name) values(?,?)"];
    
    
    /***
     如果设置了主键
     INSERT INTO msgTable(bookId, name) values(?,?)
     
     Unknown error finalizing or resetting statement (19: UNIQUE constraint failed: msgTable.bookId)
     应为有主键约束,相同主键会导致插入失败
     */
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO msgTable(msgId, content) values(?,?)"];
    
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        //将一个对象归档 --->NSData
        NSData *archData = [NSKeyedArchiver archivedDataWithRootObject:model];
        BOOL isSuccess = [db executeUpdate:sql,model.msgId,archData];
        
        FDLog(@"%@",isSuccess ? @"插入成功" : @"插入失败");
    }];
}


/**2.查询所有的数据*/
- (NSArray *)selectAllMessage {
    //容器
    NSMutableArray *vesselArrM = @[].mutableCopy;
    
    //2.sql语句
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM msgTable"];
    //3.执行sql
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        FMResultSet *res = [db executeQuery:sqlStr];
        while ([res next]) {
            
            //3-1查询结果
            //            NSString *msgId = [res stringForColumn:@"msgId"];
            NSData *tempData = [res dataForColumn:@"content"]; //NSData
            
            //3-2解档
            PushMsgModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:tempData];
            
            FDLog(@"=========:%@",model);
            //非空才添加
            if (model != nil) {
                //3-3存入数组中
                [vesselArrM addObject:model];
            }
        }
    }];
    
    //4.返回
    return [vesselArrM copy];
}

/**3.删除一条消息*/
- (void)deleteMessageModelMsgId:(NSString *)msgId {
    //1.sql语句, 根据msgId 删除
    NSString *sqlStr = [NSString stringWithFormat:@"DELETE FROM msgTable WHERE msgId = %@",msgId];
    
    //2.执行sql语句
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        BOOL isDeleteSuccess = [db executeUpdate:sqlStr];
        FDLog(@"%@",isDeleteSuccess ? @"删除成功" : @"删除失败");
    }];
}

/**4.删除d所有的数据*/
- (void)deleteAllMessage {
    //1.sql语句
    
    //2.执行sql
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        BOOL isDeleteOk = [db executeUpdate:@"DELETE FROM msgTable"];
        FDLog(@"%@",isDeleteOk ? @"删除成功" : @"删除失败");
    }];
}

/**5.更新读写状态  已读 未读*/
- (void)updateReadStateWithMsgId:(NSString *)msgId {
    //①②③⑤④
    
    //①取出来改状态
    PushMsgModel *model = [self selectMsgModleWithMsgId:msgId];
    //修改model的状态 重新归档
    model.isRead = YES; //已读
    
    //②删
    [self deleteMessageModelMsgId:msgId];
    
    //③ 重新存
    [self addMessageModel:model];
}






/**6.批量更新读写状态 一键已读*/
- (void)updateReadAll {
    
}

/**6.查询某一条数据*/
- (PushMsgModel *)selectMsgModleWithMsgId:(NSString *)msgId {
    NSString *sql = [NSString stringWithFormat:@"SELECT  FROM msgTable WHERE msgId = %@",msgId];
    
    __block PushMsgModel *model = nil;
    [self.dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        
        FMResultSet *res = [db executeQuery:sql];
        while ([res next]) {
            //查询结果
            NSData *tempData = [res dataForColumn:@"content"]; //NSData
            
            //解档
            model = [NSKeyedUnarchiver unarchiveObjectWithData:tempData];
        }
    }];
    
    return model;
}
@end
